package com.nhh.v.utils

import java.awt.RenderingHints
import java.awt.image.BufferedImage
import java.io.File
import java.text.SimpleDateFormat

import scala.util.Try

import com.nhh.exception.ServiceException
import com.nhh.v.cons.ServerCons
import javax.imageio.ImageIO
import org.apache.commons.codec.binary.Base64

/**
  * Created by ywp on 2018/9/6.
  */
object NhhUtil {

  private lazy val validEmail = """^([a-zA-Z0-9.!#$%&’'*+/=?^_`{|}~-]+)@([a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*)$""".r
  private lazy val validMobile1 = """+861[73458]{1}\d{9}$""".r
  private lazy val validMobile2 = """1[73458]{1}\d{9}$""".r
  private lazy val validMobile3 = """+d{8,20}$""".r


  /**
    * 获取头像方法
    * 适配java和scala动态类型
    *
    * @param para
    * @return
    */
  def getHeadImgUrl(para: AnyRef): String = {
    val url = para match {
      case s: String ⇒ s
      case value: {def headimgurl: String; def getHeadimgurl: String} ⇒
        Try(value.headimgurl).getOrElse(value.getHeadimgurl)
      case _ ⇒ throw new ServiceException(ServerCons.defaultErrorCode, ServerCons.headImgUrlNotFound)
    }

    if (url.toLowerCase.startsWith("http")) url else ServerCons.RESURL
  }

  def formatNHH(nhhcoins: BigDecimal, dec: Int = 3): String = if (nhhcoins > 10000) s"${format(nhhcoins / 10000, dec)}万" else format(nhhcoins, dec)

  def format(nhhcoins: BigDecimal, dec: Int): String = dec match {
    case 2 ⇒ FormatterUtil.format(nhhcoins.bigDecimal)
    case _ ⇒ FormatterUtil.format(nhhcoins)
  }

  def base64Decode(text: String): String = {
    val base64 = new Base64()
    return new String(base64.decode(text), "UTF-8")
  }

  def resize(src: String, to: String, newWidth: Int, newHeight: Int): Unit = {
    val srcFile = new File(src)
    val toFile = new File(to)
    val img = ImageIO.read(srcFile)
    val w = img.getWidth()
    val h = img.getHeight()
    val dimg  = new BufferedImage(newWidth, newHeight, img.getType())
    val g = dimg.createGraphics()
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
    g.drawImage(img, 0, 0, newWidth, newHeight, 0, 0, w, h, null)
    g.dispose()
    ImageIO.write(dimg, "png", toFile)
  }

  def isEmail(email: String): Boolean = email match {
    case validEmail(_, _) => true
    case _ ⇒ false
  }

  def isMobile(mobile: String): Boolean = mobile match {
    case "+" ⇒ validMobile1.findFirstIn(mobile).nonEmpty
    case "+86" ⇒ validMobile2.findFirstIn(mobile).nonEmpty
    case _ ⇒ validMobile3.findFirstIn(mobile).nonEmpty
  }
}

